// pages/usercenter/cabinetapply/cabinetapply.js
const userModel = require('../../../model/user');
const districtsData = require('../../../assets/districts');
const {fetchCabinetBundle} = require('../../../services/cabinetbundle/fetchCabinetBundle');
const {updateApplication, applicationCabinetOwner, generateAndUpdateQrcode} = require('../../../services/cabinet/cabinet');
const { getUserAddresses } = require('../../../services/address/address');
const addressManager = require('../../../model/address');
const globalModel = require('../../../model/global');

Page({
  data: {
    multiArray: [[], []], // 省、市数据
    multiIndex: [0, 0],
    keys: [[], []],
    role: '', // 用户角色
    name: '',
    phone: '',
    wineType: '', // 酒窖类型
    deposit: 0, // 保证金金额
    wineInfo: [], // 酒窖信息
    cabinetBundles: [], // 从接口获取的酒窖数据
    selectedCabinet: {}, // 选择的酒窖
    wineTotalPrice: 0, // 酒的总价
    inviteCode: '', //邀请码
    selectedAddress: {},
    servicePhone: '',
  },

  async onLoad() {
    const userData = userModel.getUserData();
    const servicePhone = globalModel.getServicePhone() || '138xxxx';
    this.setData({
      role: userData.info.role,
      name: userData.info.username, // 填充用户名
      phone: userData.info.phone,   // 填充手机号
      servicePhone: servicePhone,
    });
    this.initializeRegionList();
    await this.fetchCabinetBundles();
    this.wineType = '优选酒窖';
    this.showCabinetType(this.wineType);
  },

  async onShow() {
    this.loadAddresses();
  },

  async loadAddresses() {
    try {
      const serverAddresses = await getUserAddresses();
      const localAddresses = addressManager.getAllAddresses();

      // 合并本地和服务器地址列表
      const mergedAddresses = serverAddresses.map((serverAddress) => {
        const localAddress = localAddresses[serverAddress.id];
        return {
          ...serverAddress,
          isDefault: localAddress?.isDefault || false, // 优先使用本地的 isDefault 信息
        };
      });

      // 确定选中的地址
      const selectedAddressId = addressManager.getSelectedAddressId();
      let selectedAddress = {};

      if (mergedAddresses.length > 0) {
        if (selectedAddressId) {
          selectedAddress = mergedAddresses.find((addr) => addr.id === selectedAddressId) || {};
        }

        if (!selectedAddress.id) {
          const defaultAddresses = mergedAddresses.filter((addr) => addr.isDefault);
          selectedAddress = defaultAddresses.length > 0 ? defaultAddresses[0] : mergedAddresses[0];
        }
      }

      this.setData({
        addresses: mergedAddresses,
        selectedAddress: selectedAddress || {},
      });
    } catch (error) {
      console.error('加载地址失败', error);
    }
  },

  // 回调：当 address-card 内部调用 triggerEvent('select', { address }) 时，会触发这个方法
  onSelectAddress(e) {
    const { address } = e.detail;
    // address-card 组件传回的地址对象，比如 { province: 'xx', city: 'xx', district: 'xx', detail: 'xxx' }
    this.setData({ selectedAddress: address });
  },

  async fetchCabinetBundles() {
    try {
      const cabinetBundles = await fetchCabinetBundle();
      this.setData({ cabinetBundles });
    } catch (err) {
      console.error('Failed to fetch cabinet bundles:', err);
      wx.showToast({ title: '无法加载酒窖数据', icon: 'none' });
    }
  },

  initializeRegionList() {
    const provinces = Object.entries(districtsData['00']);
    const firstProvinceKey = provinces[0][0];
    const cities = Object.entries(districtsData[firstProvinceKey]);

    this.setData({
      multiArray: [
        provinces.map(([_, name]) => name),
        cities.map(([_, name]) => name),
      ],
      keys: [
        provinces.map(([key]) => key),
        cities.map(([key]) => key),
      ],
    });
  },
  
  handleColumnChange(e) {
    const { column, value } = e.detail;
    const { keys, multiArray } = this.data;

    if (column === 0) {
      const selectedProvinceKey = keys[0][value];
      const cities = Object.entries(districtsData[selectedProvinceKey]);

      this.setData({
        'multiArray[1]': cities.map(([_, name]) => name),
        'keys[1]': cities.map(([key]) => key),
        'multiIndex[0]': value,
        'multiIndex[1]': 0,
      });
    } else if (column === 1) {
      this.setData({
        'multiIndex[1]': value,
      });
    }
  },

  handleInputChange(e) {
    const { field } = e.currentTarget.dataset;
    const { value } = e.detail;
    this.setData({
      [field]: value,
    });
  },

  showCabinetType(type) {
    const selectedCabinet = this.data.cabinetBundles.find(bundle => bundle.name === type);
    
    if (selectedCabinet) {
        let wTotalPrice = 0;
        selectedCabinet.wines.forEach((w) => {
            wTotalPrice += w.price * w.quote;
        })
      this.setData({
        wineType: type,
        deposit: selectedCabinet.price,
        wineInfo: selectedCabinet.wines.map(wine => `${wine.name} ${wine.aroma} ${wine.alcoholContent}度`),
        selectedCabinet: selectedCabinet,
        wineTotalPrice: wTotalPrice,
      });
    }
  },

  selectWineType(e) {
    const { type } = e.currentTarget.dataset;
    console.log("type:", type);
    this.showCabinetType(type);
  },

  async handleSubmit() {
    if (!this.data.name || !this.data.phone || !this.data.wineType || !this.data.inviteCode || 
      !this.data.selectedAddress ||
      Object.keys(this.data.selectedAddress).length === 0) {
      wx.showToast({
        title: '请填写完整信息',
        icon: 'none',
      });
      return;
    }
    wx.showLoading({ title: '提交中...' });
    const user = userModel.getUserData(); // 获取用户信息
    let wxPayArgs;
    try {
      wxPayArgs = await applicationCabinetOwner({
        bundleId: this.data.selectedCabinet.id,
        userId: user.info.id,
        username: this.data.name, // 传入用户名
        phone: this.data.phone, // 传入手机号
        openid: user.info.openid,
        inviteCode:this.data.inviteCode,
        shippingAddressId: this.data.selectedAddress.id,
      });
      if (!wxPayArgs) {
        throw new Error("applicationCabinetOwner returned null"); // 抛出错误以便统一处理
      }
    } catch (e) {
      wx.showToast({
        title: e && e.message || '申请失败，联系客服',
        icon: 'none',
      });
      wx.hideLoading();
      return;
    }
    const { applicationId, channelOrderId, ...payArgs } = wxPayArgs;
    try {
      await wx.requestPayment({
          ...payArgs,
      });

      wx.showToast({
          title: '提交成功，等待审核',
          icon: 'success',
      });

      // 支付成功后立即生成二维码并更新数据库
      try {
          const {qrCodeBase64, qrCodeUrl} = await generateAndUpdateQrcode(user.info.id, applicationId);
          await updateApplication({ id: applicationId, status: 'PENDING', channelOrderId });
      } catch (qrcodeError) {
          console.error("生成或更新二维码失败:", qrcodeError);
          wx.showToast({
              title: '提交成功，但二维码生成失败，请联系客服', // 提示用户
              icon: 'none'
          });
          await updateApplication({ id: applicationId, status: 'PENDING', channelOrderId});//即使二维码生成失败，也要更新状态
      }

      wx.navigateTo({ url: '/pages/usercenter/apply-result/index' });
    } catch (res) {
        console.error("支付失败:", res);
        let errorMsg = '支付失败';
        if (res && res.errMsg === "requestPayment:fail cancel") {
            errorMsg = '取消支付';
        }

        wx.showToast({
            title: errorMsg,
            icon: 'error'
        });
        try {
            await updateApplication({ id: applicationId, status: 'FAIL', channelOrderId });
        } catch (updateError) {
            console.error("更新申请状态为失败也失败:", updateError);
            wx.showToast({
                title: '更新申请状态失败，请联系客服',
                icon: 'none'
            });
        }
    } finally {
        wx.hideLoading();
    }
  },
});